<template>
   <div>
        <div v-if="isArrayLikeType" clas='system-sm-semibold mb-1 flex h-6 items-center gap-1 text-text-secondary'>
          <div class='truncate'>
            <div v-if="typeof payload.label === 'object'" class='flex h-full items-center'>
                <div v-if="!payload.label.isChatVar" class='flex items-center'>
                  <div class='mx-0.5 max-w-[150px] truncate text-xs font-medium text-gray-700' >
                    {{payload.label.nodeName}}
                  </div>
                </div>
              <div class='flex items-center text-primary-600'>
                <div :class="cn('ml-0.5 max-w-[150px] truncate text-xs font-medium', payload.label.isChatVar && 'text-text-secondary')"  >
                  {{payload.label.variable}}
                </div>
              </div>
            </div>
            {{typeof payload.label !== 'object' ? payload.label : ''}}

          </div>
          <span v-if="!payload.required " class='system-xs-regular text-text-tertiary'>（选填）</span>
        </div>
      <div className='grow'>
          <Input v-if=" type === InputVarType.textInput"
            :value="value || ''"
            @change="e => onChange(e.target.value)"
            placeholder="请输入"
            :autoFocus="autoFocus"
          />

            <InputNumber v-if="type === InputVarType.number "
              :value="value || ''"
              @change="e => onChange(e.target.value)"
              placeholder="请输入"
              :autoFocus="autoFocus"
            />

            <Textarea v-if="type === InputVarType.paragraph "
               :value="value || ''"
               @change="e => onChange(e.target.value)"
               placeholder="请输入"
              :autoFocus="autoFocus"
            />

            <Select v-if="type === InputVarType.select"
              class="w-full"
              :defaultValue="value || ''"
              :items="payload.options?.map(option => ({ name: option, value: option })) || []"
              @select="i => onChange(i.value)"
              :allowSearch="false"
            />

            <CodeEditor v-if="type === InputVarType.json"
              :value="value"
              :title="JSON"
              @change="onChange"
            />
          <FileUploaderInAttachmentWrapper v-if="type === InputVarType.singleFile"
            :value="singleFileValue"
            @change="handleSingleFileChange"
            :fileConfig="{
              allowed_file_types: inStepRun
                ? [
                  SupportUploadFileTypes.image,
                  SupportUploadFileTypes.document,
                  SupportUploadFileTypes.audio,
                  SupportUploadFileTypes.video,
                ]
                : payload.allowed_file_types,
              allowed_file_extensions: inStepRun
                ? [
                  ...FILE_EXTS[SupportUploadFileTypes.image],
                  ...FILE_EXTS[SupportUploadFileTypes.document],
                  ...FILE_EXTS[SupportUploadFileTypes.audio],
                  ...FILE_EXTS[SupportUploadFileTypes.video],
                ]
                : payload.allowed_file_extensions,
              allowed_file_upload_methods: inStepRun ? [TransferMethod.local_file, TransferMethod.remote_url] : payload.allowed_file_upload_methods,
              number_limits: 1,
              fileUploadConfig: fileSettings?.fileUploadConfig,
            }"
          />
          <FileUploaderInAttachmentWrapper v-if="type === InputVarType.multiFiles"
            :value="value"
            @change="files => onChange(files)"
            :fileConfig="{
              allowed_file_types: inStepRun
                ? [
                  SupportUploadFileTypes.image,
                  SupportUploadFileTypes.document,
                  SupportUploadFileTypes.audio,
                  SupportUploadFileTypes.video,
                ]
                : payload.allowed_file_types,
              allowed_file_extensions: inStepRun
                ? [
                  ...FILE_EXTS[SupportUploadFileTypes.image],
                  ...FILE_EXTS[SupportUploadFileTypes.document],
                  ...FILE_EXTS[SupportUploadFileTypes.audio],
                  ...FILE_EXTS[SupportUploadFileTypes.video],
                ]
                : payload.allowed_file_extensions,
              allowed_file_upload_methods: inStepRun ? [TransferMethod.local_file, TransferMethod.remote_url] : payload.allowed_file_upload_methods,
              number_limits: inStepRun ? 5 : payload.max_length,
              fileUploadConfig: fileSettings?.fileUploadConfig,
            }"
          />
            <TextGenerationImageUploader v-if=" type === InputVarType.files"
              :settings="{
                ...fileSettings,
                detail: fileSettings?.image?.detail || Resolution.high,
                transfer_methods: fileSettings?.allowed_file_upload_methods || [],
              }"
              @filesChange="files => onChange(files.filter(file => file.progress !== -1).map(fileItem => ({
                type: 'image',
                transfer_method: fileItem.type,
                url: fileItem.url,
                upload_file_id: fileItem.fileId,
              })))"
            />
            <div v-if="isContext" class='space-y-2'>
                <CodeEditor v-for="(item, index)  in value"
                  :key={index}
                  :value={item}
                  :title="JSON"
                  @change={handleArrayItemChange(index)}
                >
                <template #headerRight v-if="value.length > 1">
                  <RiDeleteBinLine
                        onClick={handleArrayItemRemove(index)}
                        class='mr-1 h-3.5 w-3.5 cursor-pointer text-text-tertiary'
                      />
                </template>
              </CodeEditor>
            </div>
            <div v-if="isIterator" className='space-y-2'>
                <TextEditor v-for="(item , index) in value"
                  :key="index"
                  isInNode
                  :value="item"
                  title="内容"
                  @change={handleArrayItemChange(index)} >
                  <template #headerRight v-if="value.length > 1">
                    <RiDeleteBinLine
                        onClick={handleArrayItemRemove(index)}
                        className='mr-1 h-3.5 w-3.5 cursor-pointer text-text-tertiary' />
                </template>
              </TextEditor>
            </div>
      </div>
    </div>
</template>
<script setup lang="ts" name="FormItem">


import {
  RiDeleteBinLine,
} from '@remixicon/vue'
import type { InputVar } from '../../../../types'
import { BlockEnum, InputVarType, SupportUploadFileTypes } from '../../../../types'
import CodeEditor from '../editor/code-editor'
import { CodeLanguage } from '../../../code/types'
import TextEditor from '../editor/text-editor'
import Select from '@/app/components/base/select'
import Input from '@/app/components/base/input'
import Textarea from '@/app/components/base/textarea'
import TextGenerationImageUploader from '@/app/components/base/image-uploader/text-generation-image-uploader'
import { FileUploaderInAttachmentWrapper } from '@/app/components/base/file-uploader'
import { Resolution, TransferMethod } from '@/types/app'
import { useFeatures } from '@/app/components/base/features/hooks'
import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'
import cn from '@/utils/classnames'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import { InputNumber } from 'ant-design-vue'
import { computed } from 'vue'

type Props = {
  payload: InputVar
  value: any
  onChange: (value: any) => void
  className?: string
  autoFocus?: boolean
  inStepRun?: boolean
}
const props = defineProps<Props>();
  const { type } = props.payload;
  const fileSettings = useFeatures(s => s.features.file)
  const handleArrayItemChange = (index: number) => {
    return (newValue: any) => {
      props.value[index] = newValue
      props.onChange(props.value)
    }
  }
  const handleArrayItemRemove = (index: number) => {
    return () => {
      props.value.splice(index, 1)
      props.onChange(newValues)
    }
  }

  const isArrayLikeType = computed(()=> [InputVarType.contexts, InputVarType.iterator].includes(props.payload.type));
  const isContext =computed(()=> props.payload.type === InputVarType.contexts) 
  const isIterator = computed(()=> props.payload.type === InputVarType.iterator)
  const singleFileValue = computed(()=>  {
    if (props.payload.variable === '#files#')
      return props.value?.[0] || []
    return props.value ? [props.value] : []
  })
  const handleSingleFileChange = (files: FileEntity[]) => {
    if (props.payload.variable === '#files#')
       props.onChange(files)
    else if (files.length)
       props.onChange(files[0])
    else
       props.onChange(null)
  }

</script>

